import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {message, Modal, Tooltip, Spin } from 'antd';
import { WeaLocaleProvider, WeaNewScroll } from 'ecCom';
import findIndex from 'lodash/findIndex';
import * as api from "../../api/signPlugin";
import Item from './Item';
import Workflow from './Workflow';

const {info, confirm} = Modal;
const { getLabel } = WeaLocaleProvider;
let showConfirm = false;

export default class DataList extends Component{
    constructor(props){
        super(props);
        this.state = {
            timeLineDatas: {},
            wfDialogVisible: false,
            wfDialogCancelHandle: () => {
                this.setState({wfDialogVisible: false})
            },
            wfDialogShowHandle: () => {
                this.props.hidePopHandle && this.props.hidePopHandle();
                this.setState({wfDialogVisible: true})
            },
            spinning: false
        }
    }

    componentDidMount(){
        this.getTimeLineDatas();
    }

    componentWillReceiveProps(nextProps){
        nextProps.visible && this.getTimeLineDatas();
        !nextProps.visible && this.refs.scroll && this.refs.scroll.scrollerToTop();
    }

    getTimeLineDatas = () => {
        api.getButtons().then(data => {
            if(data.status === '1'){
                this.props.setDate(data.date);
                this.setState({timeLineDatas: data}, () => {
                    const idx = findIndex(data.timeline, {needSign: '1'});
                    setTimeout(() => {
                        // console.debug($(this.refs[`item${idx}`]))
                        const dom = ReactDOM.findDOMNode(this.refs[`item${idx}`]);
                        const top = idx > -1 ? $(dom).position().top - 90 : -1;
                        if(this.refs.scroll){
                            if(top === -1)
                                this.refs.scroll.scrollToLast();
                            else
                                this.refs.scroll.scroll(top);
                        }
                    }, 200)
                });
            }else{
                this.props.setDate(null);
                message.error(data.message);
            }
        }, error => {})
    }

    redirectToChecking = () => {
        this.props.hide && this.props.hide();
        window.location.href = "/wui/index.html#/main/attendance/checking";
    }

    convertStatus = v => {
        switch(v){
            case '0': return {label: getLabel('225','正常'), className: 'normal'};
            case '1': return {label: getLabel('20081','迟到'), className: 'abnormal'};
            case '2': return {label: getLabel('20082','早退'), className: 'abnormal'};
            case '3': return {label: getLabel('20085','旷工'), className: 'abnormal'};
            case '4': return {label: getLabel('20086','漏签'), className: 'abnormal'};
            case '5': return {label: getLabel('26198','外勤'), className: 'abnormal'};
            case 'auto_card': return {label: getLabel('522591','自动打卡') , className: 'autoSign'};
            default: return {label: '', className: ''};
        }
    }

    sign = params => {
        if(this.state.spinning){
            console && console.debug('spinning')
            return;
        }
        this.setState({spinning: true});
        api.punchButton(params).then(data => {
            if(data.status === '1'){
                // this.props.hidePopHandle && this.props.hidePopHandle();
                if(data.message && data.message.trim().length >0){
                    // info({ 
                    //     content: <div dangerouslySetInnerHTML={{__html: data.message}}/>,
                    //     title: getLabel(131329, '信息确认'),
                    //     okText: getLabel(33703, '确定')
                    // });
                    if(data.success === '1'){
                        message.success(data.message);
                    }else{
                        message.warning(data.message);
                    }
                }else if(['1', '2'].indexOf(data.kqstatus) > -1){
                    // confirm({
                    //     content: <div><div>{`${getLabel('18949','打卡时间')}: ${data.signdate} ${data.signtime}`}</div><div>{getLabel('500500','您的考勤数据异常，是否要提交考勤流程？')}</div></div>,
                    //     title: getLabel(131329, '信息确认'),
                    //     okText: getLabel(33703, '提交考勤流程'),
                    //     cancelText: getLabel(32694, '不需要'),
                    //     onOk: () => this.showWorkflow(),
                    //     onCancel: () => this.getTimeLineDatas()
                    // });
                    message.warning(getLabel('512595','	您的考勤数据异常，如有需要请提交考勤流程'));
                }
                this.getTimeLineDatas();
            }else{

            }
            this.setState({spinning: false});
        }, error => {this.setState({spinning: false})})
    }

    showWorkflow = () => {
        this.state.wfDialogShowHandle();
    }

    isEn = () => {
        const {e9_locale} = window;
        const {userLanguage} = e9_locale;
        return userLanguage == 8;
    }

    render(){
        const {userInfo} = this.props;
        const {timeLineDatas, wfDialogVisible, wfDialogCancelHandle} = this.state;
        const {timeline} = timeLineDatas;
        let index = -1;
        return (
            <div>
                {
                    timeline && timeline.length > 0 ?
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@5oy4j7`} spinning={this.state.spinning}>
                        <div className='content'>
                            <div className='bg' />
                            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@nmr5yy`} height='100%' ref='scroll'>
                                <div className='timeLine'>
                                    {
                                        timeline && timeline.map((item, i) => {
                                            if(item.active === '1')
                                                index = i;
                                            return (
                                                <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@wd77aa@${i}`} key={i} ref={`item${i}`} data={item} activeIndex={index} currIndex={i} sign={this.sign} isLast={i === (timeline.length - 1)} convertStatus={this.convertStatus} showWorkflow={this.showWorkflow}/>
                                            )
                                        })
                                    }
                                </div>
                            </WeaNewScroll>
                            {wfDialogVisible && <Workflow ecId={`${this && this.props && this.props.ecId || ''}_Workflow@dlrdqe`} wfDialogVisible={wfDialogVisible} wfDialogCancelHandle={wfDialogCancelHandle}/>}
                        </div>
                    </Spin>
                    :
                    <div className='content'>
                        <div style={{textAlign: 'center', lineHeight: '30px'}}>{userInfo.groupname}</div>
                    </div>
                }
                <div className={!this.isEn() ? 'flow' : 'flow-en'} >
                    {getLabel('512629', '如有打卡异常，请')+' '}
                    <a className='flow-link' onClick={this.showWorkflow}>{getLabel('132023', '提交考勤流程')+' >>'}</a>
                </div>
           
                <div className='footer'>
                    <div className='checking' onClick={this.redirectToChecking} title={getLabel(387306, '考勤报表')}>
                        <i className='icon-coms-Bar icon'/>
                        <div className='checkTitle text-elli'>{getLabel(387306, '考勤报表')}</div>
                    </div>
                    <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@zv2nak`} placement="top" title={userInfo.groupname}>
                        <i className='icon-coms-Prompt groupname'/>
                    </Tooltip>
                </div>
            </div>
        )
    }
}